﻿using System;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using PAMD.Business.Models;
using PAMD.Controllers.Helper;
using PAMD.Database.Services;
using System.Web.Security;
using PAMD.Controllers.Extension;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using PAMD.Database;
using System.Web.Script.Serialization;

namespace PAMD.Controllers.Account
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Authorize]
    public class UploadController : Controller
    {
        [Import(typeof(ProfileService))]
        private ProfileService ListingService { get; set; }

        [Import(typeof(CommonService))]
        private CommonService CommonService { get; set; }

        [Import(typeof(AccountService))]
        private AccountService AccountService { get; set; }

        public JsonResult Index()
        {
            var results = SaveFile("~/UploadToDelete/");
            return Json(results);
        }

        public JsonResult Edit()
        {
            var results = SaveFile("~/ListingPicture/");
            return Json(results);
        }

        private List<FilesResult> SaveFile(string folder)
        {
            var results = new List<FilesResult>();
            var filelist = Request.Files;
            foreach (string file in filelist)
            {
                HttpPostedFileBase postedFile = Request.Files[file];

                string fileName = string.Empty;
                string uploadPath = string.Empty;
                string error = "OK";


                if (postedFile.ContentLength > 2097152)
                {
                    error = "File size to long, file size must be less than 2MB.";
                }
                else
                {
                    if (HttpContext.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = postedFile.FileName.Split(new[] { '\\' });
                        fileName = files[files.Length - 1];
                    }
                    else
                    {
                        fileName = postedFile.FileName;
                    }

                    try
                    {
                        if (IsValidFile(fileName))
                        {
                            uploadPath = Utils.RandomNumber(10000, int.MaxValue) + fileName.Substring(0, fileName.LastIndexOf(".")) + ".jpg";
                            string savedFileName = Server.MapPath(folder) + uploadPath;

                            Image newImage = ImageProcessor.CreateStandardImage(postedFile.InputStream, 300, 300);
                            newImage.Save(savedFileName, ImageFormat.Jpeg);
                        }
                        else
                        {
                            error = "Error: Invalid file extention, Please select .png, .jpeg, .jpg or .gif image.";
                        }
                    }
                    catch (Exception ex)
                    {
                        error = "Error: Error processing image.";
                    }
                }

                results.Add(new FilesResult
                {
                    ThumbnailUrl = uploadPath,
                    Name = fileName,
                    Error = error,
                    Type = postedFile.ContentType
                });
            }

            return results;
        }

        private static bool IsValidFile(string fileName)
        {
            if (!string.IsNullOrEmpty(fileName) && fileName.Split('.').Length < 3)
            {
                return (Path.GetExtension(fileName).Equals(".jpg", StringComparison.CurrentCultureIgnoreCase)) ||
                    (Path.GetExtension(fileName).Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase)) ||
                    (Path.GetExtension(fileName).Equals(".gif", StringComparison.CurrentCultureIgnoreCase)) ||
                    (Path.GetExtension(fileName).Equals(".png", StringComparison.CurrentCultureIgnoreCase));
            }
            return false;
        }
    }

    public class FilesResult
    {
        public string ThumbnailUrl { get; set; }
        public string Name { get; set; }
        public string Error { get; set; }
        public string Type { get; set; }
    }
}